import React,{useEffect, useState} from "react";
import { Button,Form,Input,Table,Modal,Select,message, Popconfirm,Pagination  } from "antd";
import { getUser,addUser,delUserApi } from "../../../api/user"
import './index.css'
const User = () => {
    const [tableData, setTableData] = useState([])
    const [params, setParams] = useState({name:'', pageNum:1,pageSize:10})
    const [total, setTotal] = useState(0)
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modelTitle, setModelTitle] = useState(0)  //0新增 1编辑
    const [delUser, setDelUser] = useState({})
    // 创建表单form实例
    const [form] = Form.useForm();
      //获取用户列表
    const getUserData=async()=>{
      console.log('获取用户列表')
      const res = await getUser(params)
      if(res.code===200){
        setTableData(res.data.list)
        setTotal(res.data.total)
      }
    }
    useEffect(()=>{
      getUserData()
    },[params])

    // 分页
  const onPageChange = (page) => {
    console.log('Page:', page);
    //setParams({...params,pageNum:page}); // useState是异步的 更新当前页码状态
    setParams((params) =>  ({...params, pageNum: page})); //也是异步的 重新获取数据
  };
    // 搜索用户
    const handleSearch=(e)=>{
      setParams({...params,name:e.keyword})
    }
  // 删除用户
    const deleteUser=(row)=>{
      console.log(row)
      setDelUser(row)
    }
    // 新增用户 or 编辑用户 弹窗
    const handleAdd = (type,data) => {
      setIsModalOpen(true)
      if(type==='add'){
        setModelTitle(0)
      }else{
        setModelTitle(1)
        const rowData = JSON.parse(JSON.stringify(data))
        form.setFieldsValue(rowData) //回显表单
        console.log(rowData)
      }
    }
  //确认新增or 编辑用户
  const handleOk=()=>{
    console.log('ok')
    form.validateFields().then((val)=>{
      console.log(val)
      addUser(val).then((res)=>{
        if(res.code===200){
          getUserData()
          handleCancel()
        }
      })
    }).catch((err)=>{
      console.log(err)
    })
    
  }
  // 取消新增or 编辑用户
  const handleCancel=()=>{
    form.resetFields() //清空表单
    setIsModalOpen(false)
  }
  const confirm = (e) => {
    const params = {id:delUser.id}
    delUserApi(params).then((res)=>{
      if(res.code===200){
        message.success('删除成功')
        getUserData()
      }
    })
  };

  const columns =[
    {
      title: '用户名',
      dataIndex: 'name',
    },
    {
      title: '密码',
      dataIndex: 'pwd',
    },
    {
      title: '性别',
      dataIndex: 'gender',
    },
    {
      title: '电话',
      dataIndex: 'tel',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
    },
    {
      title: '操作',
      render:(row)=>{
        return (
          <div>
            <Button type="primary" size="small" onClick={()=>handleAdd('edit',row)}>编辑</Button>
            <Popconfirm
              title="确认删除"
              description="是否确认删除该用户?"
               okText="确认"
              cancelText="取消"
              onConfirm={confirm}
            >
                <Button type="danger" size="small" onClick={()=>deleteUser(row)} style={{marginLeft:'10px'}}>删除</Button>
            </Popconfirm>
          </div>
        )
      }
    }
  ]
  return (
    <div className="user">
       <div className="header">
          <Button type="primary" onClick={()=>handleAdd('add')}>新增</Button>
          <Form layout="inline" onFinish={handleSearch}>
            <Form.Item name="keyword">
              <Input placeholder="请输入关键字"></Input>
            </Form.Item>
            <Form.Item>
              <Button htmlType="submit" type="primary">搜索</Button>
            </Form.Item>
          </Form>
       </div>
       <div className="table-box">
        <Table dataSource={tableData} columns={columns} rowKey={'id'} pagination={false}/>
        <Pagination defaultCurrent={params.pageNum} total={total} onChange={onPageChange}/>
       </div>
       <Modal title={modelTitle===0?'新增用户':'编辑用户'} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
       <Form
       form={form}
       labelCol={{ span: 6 }}
       wrapperCol={{ span: 18 }}
       labelAlign="left"
      >
          <Form.Item 
          label="用户名"
          name="name"
          rules={[{ required: true, message: '请输入用户名' }]}
          >
              <Input type="text" placeholder="请输入用户名"  />
          </Form.Item>
          <Form.Item 
            label="密码"
            name="pwd"
            rules={[{ required: true, message: '请输入密码' }]}
          >
              <Input  type="password" placeholder="请输入密码" />
          </Form.Item>
          <Form.Item
             label="性别"
             name="gender"
             rules={[{ required: true, message: '请选择性别' }]}
          >
              <Select placeholder="请选择性别">
                <Select.Option value="男">男</Select.Option>
                <Select.Option value="女">女</Select.Option>
              </Select>
          </Form.Item>
          <Form.Item 
            label="电话"
            name="tel"
            rules={[{ required: true, message: '请输入电话' }]}
          >
              <Input type="text" placeholder="请输入电话"  />
          </Form.Item>
          <Form.Item 
          label="邮箱"
          name="email"
          rules={[{ required: true, message: '请输入邮箱' }]}
          >
              <Input type="text" placeholder="请输入邮箱"  />
          </Form.Item>
          {modelTitle===1 && <Form.Item name="id" hidden> <Input></Input></Form.Item>}
      </Form>
      </Modal>
     </div> 

  )
}
export default User